package db

import (
	"fmt"
	"time"

	"temp/config"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func InitDB(config config.DBConfig) (*gorm.DB, error) {
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local", config.User, config.Password,
		config.Host, config.Port, config.DBName)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		SkipDefaultTransaction: true,
		NamingStrategy:         nil,
		// FullSaveAssociations full save associations
		FullSaveAssociations: true,
		// Logger
		Logger: nil,
		// NowFunc the function to be used when creating a new timestamp
		NowFunc: time.Now,
		// DryRun generate sql without execute
		DryRun: false,
		// PrepareStmt executes the given query in cached statement
		PrepareStmt: true,
		// PrepareStmt cache support LRU expired,
		// default maxsize=int64 Max value and ttl=1h
		// DisableAutomaticPing
		DisableAutomaticPing: false,
		// DisableForeignKeyConstraintWhenMigrating
		DisableForeignKeyConstraintWhenMigrating: true,
		// IgnoreRelationshipsWhenMigrating
		IgnoreRelationshipsWhenMigrating: true,
		// DisableNestedTransaction disable nested transaction
		DisableNestedTransaction: true,
		// AllowGlobalUpdate allow global update
		AllowGlobalUpdate: true,
		// QueryFields executes the SQL query with all fields of the table
		QueryFields: false,
		// CreateBatchSize default create batch size
		CreateBatchSize: 1000,
		// TranslateError enabling error translation
		TranslateError: true,
		// PropagateUnscoped propagate Unscoped to every other nested statement

		// ClauseBuilders clause builder
		ClauseBuilders: nil,
		// ConnPool db conn pool
		ConnPool: nil,
		Plugins:  nil,
	})
	if err != nil {
		return nil, err
	}
	s, err := db.DB()
	if err != nil {
		return nil, err
	}
	s.SetMaxIdleConns(10)
	s.SetMaxOpenConns(100)
	s.SetConnMaxLifetime(time.Hour)
	autoMigrate(db)
	return db, err
}

func autoMigrate(db *gorm.DB) {
	err := db.AutoMigrate(ModelRegistry...)
	if err != nil {
		fmt.Printf("数据库迁移失败: %v\n", err)
		return
	}
	fmt.Println("数据库迁移成功")
}
